package com.axend.aerosense.room.viewmodel;


import android.app.Activity;
import android.graphics.Bitmap;
import android.text.TextUtils;

import androidx.lifecycle.MutableLiveData;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.common.ui.LoadingDialog;
import com.axend.aerosense.common.util.HeadIconUploadService;
import com.axend.aerosense.network.callback.ProgressDialogCallBack;
import com.axend.aerosense.room.entity.PersonInfoBean;
import com.axend.aerosense.room.entity.PersonEditBean;
import com.axend.aerosense.room.entity.PersonGetInfo;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.axend.aerosense.base.bean.BaseStringBean;
import com.axend.aerosense.base.impl.IBaseView;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.impl.IOperationDetailResult;
import com.axend.aerosense.base.impl.IOperationResult;
import com.axend.aerosense.base.viewmodel.CustomBaseViewModel;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.services.ILoginService;
import com.axend.aerosense.common.services.config.ServicesConfig;
import com.axend.aerosense.common.util.CheckUtil;
import com.axend.aerosense.common.util.JsonUtil;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.model.CacheMode;
import com.axend.aerosense.network.callback.SimpleCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.axend.aerosense.room.R;

import io.reactivex.disposables.Disposable;

public class PersonInfoViewModel extends CustomBaseViewModel<PersonInfoBean> {
    public MutableLiveData<PersonInfoBean> personInfo = new MutableLiveData<>(
            new PersonInfoBean(null, null, null, "1", null));
    public MutableLiveData<Boolean> edit = new MutableLiveData<>(false);
    public MutableLiveData<Boolean> editHeadImage = new MutableLiveData<>(false);

    @Autowired(name = ServicesConfig.User.LONGING_SERVICE)
    ILoginService iLoginService;
    private Disposable disposable;

    public PersonInfoViewModel(IBaseView baseViewImpl, ILoadDataResult<PersonInfoBean> loadDataResultImpl) {
        super(baseViewImpl, loadDataResultImpl);
        ARouter.getInstance().inject(this);
    }

    public void setValue(PersonInfoBean bean){
        personInfo.setValue(bean);
    }

    public void addPerson(Activity activity, Bitmap upBitmap, IOperationDetailResult<PersonInfoBean> operationResultListence){
        if(null == personInfo.getValue()){
            return;
        }
        if(TextUtils.isEmpty(personInfo.getValue().getEmergencyName())){
            ToastUtils.showShort(R.string.common_check_usename);
            return;
        }
        if(!CheckUtil.orPhoneNumber(personInfo.getValue().getEmergencyPhone())){
            ToastUtils.showShort(R.string.common_input_phone_num);
            return;
        }
        personInfo.getValue().setEmergencyImg(HeadIconUploadService.bitmapToBase64(upBitmap));
        EasyHttp.post(UrlApi.URL.AddEmergencyContact.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .headers("token", iLoginService.getToken())
                .upJson(JsonUtil.toJson(personInfo.getValue()))
                .execute(new ProgressDialogCallBack<PersonInfoBean>(LoadingDialog.getProgressDialog(activity)) {
                    @Override
                    public void onTokenExpire() {
                        dismissProgress();
                        ToastUtils.showShort(R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissProgress();
//                        ToastUtils.showShort(e.getMessage());
                        ToastUtils.showShort(e.getMessage());
                        if(null != operationResultListence){
                            operationResultListence.onFail(0, "");
                        }
                    }

                    @Override
                    public void onSuccess(PersonInfoBean bean) {
                        dismissProgress();
                        ToastUtils.showShort(Utils.getApp().getString(R.string.common_success));
                        if(null != operationResultListence){
                            operationResultListence.onSuccess(bean);
                        }
                    }
                });
    }
    public void deletePerson(Activity activity, String id, IOperationDetailResult<BaseStringBean> operationResultListence){
        PersonEditBean bean = new PersonEditBean(id);
        EasyHttp.post(UrlApi.URL.DelEmergencyContact.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(bean))
                .headers("token", iLoginService.getToken())
                .execute(new ProgressDialogCallBack<BaseStringBean>(LoadingDialog.getProgressDialog(activity)) {
                    @Override
                    public void onTokenExpire() {
                        dismissProgress();
                        if(null != operationResultListence){
                            // 此处只是为了关闭提示窗口
                            operationResultListence.onFail(Gobal.ERROR_CODE.ERR_LOGIN, "");
                        }
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissProgress();
                        ToastUtils.showShort(e.getMessage());
                        if(null != operationResultListence){
                            operationResultListence.onFail(Gobal.ERROR_CODE.ERR_DELETE, e.getMessage());
                        }
                    }

                    @Override
                    public void onSuccess(BaseStringBean bean) {
                        dismissProgress();
                        ToastUtils.showShort(Utils.getApp().getString(R.string.common_success));
                        if(null != operationResultListence){
                            operationResultListence.onSuccess(bean);
                        }
                    }
                });
    }

    public void getPerson(String id){
        if(TextUtils.isEmpty(id)){
            return;
        }
        PersonEditBean bean = new PersonEditBean(id);
        disposable = EasyHttp.post(UrlApi.URL.GetPerson.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .headers("token", iLoginService.getToken())
                .upJson(JsonUtil.toJson(bean))
                .execute(new SimpleCallBack<PersonGetInfo>() {
                    @Override
                    public void onTokenExpire() {
                        ToastUtils.showShort(R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.showShort(e.getMessage());
                        loadDataFail(e.getDisplayMessage());
                    }

                    @Override
                    public void onSuccess(PersonGetInfo bean) {
                        loadDataSuccess(bean.emergencyInfo);
                    }
                });
    }

    public void updatePerson(Activity activity, IOperationResult operationResultListence){
        if(null == personInfo.getValue()){
            return;
        }

        if(TextUtils.isEmpty(personInfo.getValue().getEmergencyName())){
            ToastUtils.showShort(R.string.common_check_usename);
            return;
        }
        if(!CheckUtil.orPhoneNumber(personInfo.getValue().getEmergencyPhone())){
            ToastUtils.showShort(R.string.common_input_phone_num);
            return;
        }

        EasyHttp.post(UrlApi.URL.UpdatePerson.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .headers("token", iLoginService.getToken())
                .upJson(JsonUtil.toJson(personInfo.getValue()))
                .execute(new ProgressDialogCallBack<BaseStringBean>(LoadingDialog.getProgressDialog(activity)) {
                    @Override
                    public void onTokenExpire() {
                        dismissProgress();
                        ToastUtils.showShort(R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissProgress();
                        ToastUtils.showShort(e.getMessage());
                        if(null != operationResultListence){
                            operationResultListence.onFail();
                        }
                    }

                    @Override
                    public void onSuccess(BaseStringBean bean) {
                        dismissProgress();
                        ToastUtils.showShort(Utils.getApp().getString(R.string.common_success));
                        if(null != operationResultListence){
                            operationResultListence.onSuccess();
                        }
                    }
                });
    }



    @Override
    public void onLoad() {

    }

    @Override
    protected void onCleared() {
        if(null != disposable && !disposable.isDisposed()){
            disposable.dispose();
            disposable = null;
        }
        super.onCleared();
    }
}
